package task

import (
	"strconv"

	"github.com/xuelang-group/sh-solver-scheduler/internal/domain/entity"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/utils/pointer"
)

// 求解器 service
func GetSolverDeployment(task *entity.SolverTask) (*appsv1.Deployment, error) {
	container, err := getSolverContainer(task)
	if err != nil {
		return nil, err
	}

	labels := GetDefaultLabels(task.ID)

	template := corev1.PodTemplateSpec{
		ObjectMeta: metav1.ObjectMeta{
			Labels: labels,
		},
		Spec: corev1.PodSpec{
			RestartPolicy: corev1.RestartPolicyAlways,
			Containers:    []corev1.Container{*container},
		},
	}

	// if parse err, default to 1
	replicas := 1

	// TODO ok
	deployment := appsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      strconv.Itoa(task.ID),
			Namespace: task.Namespace,
			Labels:    labels,
		},

		Spec: appsv1.DeploymentSpec{
			Replicas: pointer.Int32Ptr(int32(replicas)),
			Selector: &metav1.LabelSelector{
				MatchLabels: labels,
			},
			Template: template,
		},
	}

	return &deployment, nil
}
